package com.atguigu.gmall.product.controller;

import com.atguigu.gmall.common.result.Result;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.Objects;

/**
 * @author Fxz
 * @version 1.0
 * @date 2022-02-05 18:52
 */
@Slf4j
@RestController
@RequestMapping("/admin/product")
public class FileUpdateController {

	@Value("${fileServer.url}")
	private String fileServiceUrl;

	/**
	 * 1.加载配置文件 2.初始化当前文件 3.创建TrackerClient 4.创建TrackerServer 5.创建StorageClient1 6.文件上传
	 */
	@SneakyThrows
	@PostMapping("/fileUpload")
	public Result fileUpload(MultipartFile file) {
		String path = StringPool.EMPTY;
		String configFile = Objects.requireNonNull(this.getClass().getResource("/tracker.conf")).getFile();
		if (configFile != null) {
			// 初始化
			ClientGlobal.init(configFile);
			// 创建TrackerClient
			TrackerClient trackerClient = new TrackerClient();
			// 创建TrackerServer
			TrackerServer trackerServer = trackerClient.getConnection();
			// 创建StorageClient1
			StorageClient1 storageServer = new StorageClient1(trackerServer, null);
			// 获取文件后缀名
			String extension = FilenameUtils.getExtension(file.getOriginalFilename());
			// 文件上传
			path = storageServer.upload_appender_file1(file.getBytes(), extension, null);
		}
		log.info("文件地址是:{}", fileServiceUrl + path);
		// 返回最终路径
		return Result.ok(fileServiceUrl + path);
	}

}
